package com.itheima.aspect;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LogInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class LoginAspect {
    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        log.info("登录日志");
        //计算耗时
        long begin = System.currentTimeMillis();
        EmpLoginLog empLoginLog = new EmpLoginLog();
        Object[] args = pjp.getArgs();
        if(null != args && args.length>0){
            empLoginLog.setUsername(((Emp) args[0]).getUsername());
            empLoginLog.setPassword(((Emp) args[0]).getPassword());
        }
        Object rtn=null;
        try {
            rtn=pjp.proceed();
            Result result=(Result) rtn;
            empLoginLog.setIsSuccess(result.getCode().shortValue());
            if (result.getCode()==1){
                LogInfo logInfo=(LogInfo) result.getData();
                empLoginLog.setJwt(logInfo.getToken());
            }
        } catch (Throwable e) {
            empLoginLog.setIsSuccess((short)0);
            throw e;
        }finally{
            long end = System.currentTimeMillis();
            empLoginLog.setCostTime(end-begin);
            empLoginLogMapper.insert(empLoginLog);
        }
        return rtn;
    }
}
